package com.lagou.edu.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @ClassName: ResourceUtil
 * @Auther: Jerry
 * @Date: 2020/7/31 0:21
 * @Desctiption: 静态资源工具类
 * @Version: 1.0
 */
public class ResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     * @param path 路径
     * @return {@link String}
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = ResourceUtil.class.getResource("/").getPath();
        return absolutePath.replace("\\\\", "/") + path;
    }

    /**
     * 读取输入流，并将流信息转换成静态资源输出
     * @param inputStream 文件输入流
     * @param outputStream 输出流
     */
    public static void outputResource(FileInputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;

        while (count == 0) {
            count = inputStream.available();
        }

        int resourceSize = count;
        // 输出http请求头
        outputStream.write(HttpProtocolUtil.getHeader200(resourceSize).getBytes());

        // 已读长度
        long writen = 0;
        // 缓冲长度
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];

        while (writen < resourceSize) {
            if (writen + byteSize > resourceSize) {
                // 剩余文件长度
                byteSize = (int) (resourceSize - writen);
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            writen += byteSize;
        }
    }
}
